import wxValidate from 'wechat-validate'
const app = getApp()
Page({
    data: {
        countDownVisible: false,
        mobile: '',
        code: ''
    },
    onLoad({
        redirectURL,
        routeType
    }) {
        this.redirectURL = redirectURL
        this.routeType = routeType
    },
    behaviors: [wxValidate],
    rules: {
        mobile: [{
                required: true,
                message: '请填写手机号'
            },
            {
                pattern: /^1[3-8]\d{9}$/,
                message: '请填写正确的手机号'
            }
        ],
        code: [{
                required: true,
                message: '请填写验证码!'
            },
            {
                pattern: /^\d{6}$/,
                message: '请填写正确的验证码!'
            }
        ],
    },
    countDownChange(ev) {
        this.setData({
            timeData: ev.detail,
            countDownVisible: ev.detail.minutes === 1 || ev.detail.seconds > 0,
        })
    },
    async getSMSCode() {
        const {
            valid,
            message
        } = this.validate('mobile')
        console.log(valid, message)
        if (!valid) return wxValidate.utils.toast(message)
        this.setData({
            countDownVisible: true
        })
        // 调用接口获取验证码
        const {
            code,
            data
        } = await wx.http.get('/code', {
            mobile: this.data.mobile
        })
        // 检测验证码是否发送成功
        if (code !== 10000) return wx.utils.toast('发送失败，稍后重试!')
    },
    // 提交表单数据，完成登录/注册的功能
    async submitForm() {
        // 验证数据是否合法
        if (!this.validate()) return
        // 调用登录接口
        const {
            code,
            data
        } = await wx.http.post('/login', {
            mobile: this.data.mobile,
            code: this.data.code
        })
        // 验证是否登录成功
        if (code !== 10000) return wx.utils.toast('登录失败，稍后重试!')

        // 存储 token 数据
        app.setToken('token', data.token)
        app.setToken('refreshToken', data.refreshToken)

        // 跳转到新的页面
        wx[this.routeType]({
            url: this.redirectURL
        })
    }
})